<template>
  <div class="Images">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 头部 -->
        <myel-header text1="首页" text2="素材管理" v-show="!iskai"></myel-header>
      </div>
      <!-- 下面 -->
      <div>
        <!-- 仨按钮 -->
        <div>
          <span class="left">
            <el-radio-group v-model="collect" @change="onqiehuan" size="small">
              <el-radio-button :label="false">全部</el-radio-button>
              <el-radio-button :label="true">收藏</el-radio-button>
            </el-radio-group>
          </span>
          <!-- 上传图片 -->
          <span class="right">
            <!-- 弹出框 -->
            <el-button
              type="success"
              @click="dialogVisible = true"
              size="small"
              :destroy-on-close="true"
              v-if="!iskai"
            >添加图片素材</el-button>
            <el-button
              type="success"
              @click="shangchuan"
              size="small"
              :destroy-on-close="true"
              v-else
            >上传</el-button>
            <el-dialog
              title="上传素材"
              :visible.sync="dialogVisible"
              width="30%"
              :before-close="handleClose"
              append-to-body
              close-on-press-escape
              :show-close="false"
              v-if="!iskai"
            >
              <!-- 弹出框里的上传 -->
              <span>
                <el-upload
                  class="avatar-uploader"
                  action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
                  :headers="headers"
                  :show-file-list="false"
                  name="image"
                  :on-success="handleSuccess"
                  :before-upload="beforeUpload"
                  :on-error="onError"
                >
                  <template>
                    <el-alert title="温馨提示：只允许上传jpg格式" type="warning" :closable="false"></el-alert>
                  </template>
                  <br>
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </span>
            </el-dialog>
          </span>
        </div>
        <!-- 图片展示 -->
        <div style="margin-top: 10px;margin-top: 10px;">
          <el-row :gutter="24">
            <el-col v-for="(item, i) in imagoods" :key="i" :xs="12" :sm="6" :md="4">
              <div class="image-box">
                <el-image :src="item.url" fit="cover" @click="onwujiaoxin(item)"></el-image>
                <!-- 图片操作 -->
                <div class="image-act" v-if="!iskai">
                  <span
                    class="el-icon-star-on"
                    :style="item.is_collected?'color:rgb(255, 208, 75)':''"
                    @click="onxinxin(item)"
                  ></span>
                  <span class="el-icon-delete" @click="onimgdel(item.id,i)"></span>
                </div>
                <!-- 大型五角心 -->
                <div v-else>
                  <span class="el-icon-star-off duigou" v-show="item.iswujiaoxin"></span>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- 分页 -->
        <div>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            @current-change="pages"
          ></el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
// 头部
import MyelHeader from '@/components/MyelHeader.vue'
import { getimages, putimages, delimages } from '@/api/articles.js'
import { getToken } from '@/api/usertoken.js'
export default {
  name: 'Images',
  components: {
    MyelHeader
  },
  props: {
    iskai: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: '1'
    }
  },
  emits: ['zigofu'],
  data () {
    return {
      // 布尔值
      isrute: false,
      // 弹出框
      dialogVisible: false,
      // 图片素材
      imagoods: [],
      // 每页图片个数
      per_page: 12,
      // 图片总数
      total: 0,
      // 当前页数
      page: 1,
      // 布尔改变全部收藏
      collect: false,
      // 上传的参数
      headers: {
        Authorization: `Bearer ${getToken().token}`
      },
      // 弹出框里的上传
      imageUrl: '',
      // 封面的上传
      fengurl: ''
    }
  },
  created () {
    this.imagesgoods()
  },
  methods: {
    // 获取图片素材
    async imagesgoods () {
      const { data: { data } } = await getimages(
        {
          per_page: this.per_page,
          page: this.page,
          collect: this.collect
        }
      )
      // 追加一个布尔值控制选中显示大五角星
      data.results.forEach(element => {
        element.iswujiaoxin = false
      })
      this.imagoods = data.results
      // 总页数
      this.total = data.total_count
    },
    // 弹出框
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    // 弹出框里的上传
    // 文件上传成功时调用的钩子
    handleSuccess (res) {
      this.imageUrl = res.data.url
      this.dialogVisible = false
      this.$message.success('上传素材成功')
      this.imageUrl = ''
      this.imagesgoods()
    },
    // 文件上传失败时调用的钩子
    onError (res) {
      this.$message.error('上传素材失败')
    },
    // 上传前
    beforeUpload (file) {
      // 文件格式
      const isJPG = file.type === 'image/jpeg'
      // 文件大小
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是jpg格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 切换全部、收藏
    onqiehuan (res) {
      this.collect = res
      this.imagesgoods()
    },
    // 点击改变星星颜色
    async onxinxin (item) {
      try {
        await putimages(item.id, !item.is_collected)
        item.is_collected = !item.is_collected
        this.$message({
          message: '执行成功',
          type: 'success'
        })
      } catch (error) {
        this.$message('执行失败')
      }
    },
    // 点击删除
    async onimgdel (id, i) {
      try {
        await delimages(id)
        // this.imagoods.splice(i, 1)
        this.imagesgoods()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {
        this.$message('删除失败')
      }
    },
    // 分页
    // 当前页数
    pages (res) {
      this.page = res
      this.imagesgoods()
    },
    // 控制五角心
    onwujiaoxin (item) {
      if (!this.iskai) return
      this.imagoods.forEach(qwe => {
        qwe.iswujiaoxin = false
      })
      item.iswujiaoxin = !item.iswujiaoxin
      this.fengurl = item.url
    },
    // 点击上传
    shangchuan () {
      this.$emit('zigofu', this.fengurl)
      this.imagoods.forEach(qwe => {
        qwe.iswujiaoxin = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.right {
  float: right;
}
// 上传样式
.avatar-uploader {
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #222;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #ccc;
  border-radius: 10px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
// 图片展示布局样式
.el-col {
  border-radius: 4px;
}
.block {
  width: 100%;
  height: 100%;
}
.image-box {
  position: relative;
  height: 150px;
  margin-bottom: 10px;
  overflow: hidden;
  cursor: pointer;
  .el-image {
    height: 100%;
  }
  .image-act {
    bottom: -20px;
  }
  .duigou {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    color: #ffd04b;
    font-size: 50px;
  }
}
.image-box:hover .image-act {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 30px;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  text-align: center;
  transition: all 0.5s ease;
  cursor: pointer;
  span {
    flex: 1;
    height: 30px;
    line-height: 30px;
    color: #fff;
    transition: background 0.2s linear;
    &:hover {
      background: #40a0ffcc;
    }
  }
}
</style>
